<template>
  <view>
    <view class="integral-details">
      <view class="header">
        <view class="nav acea-row" style="display: flex; align-items: center">
          <view class="item">
            <view class="currentScore">平台积分</view>
            <view class="scoreNum font-s36">{{ userInfo.gpWyPaymentAmount || 0 }}</view>
            <view class="line"></view>
          </view>
        </view>
      </view>
      <view class="wrapper">
        <view class="nav acea-row">
          <view class="item acea-row row-center-wrapper" :class="current == 1 ? 'on' : ''" @click="nav(1)"> <text class="iconfont icon-iconfontzhizuobiaozhun0231"></text>赠送补贴 </view>
          <view class="item acea-row row-center-wrapper" :class="current == 0 ? 'on' : ''" @click="nav(0)"> <text class="iconfont icon-tishengfenzhi"></text>平台积分明细 </view>
        </view>
        <view class="list" :hidden="current != 0">
          <view class="tip acea-row row-middle">
            <text class="iconfont icon-shuoming"></text>
            <text style="color: #ff7604">提示：此处为平台积分使用记录哦～(可用来消费折扣)</text>
          </view>
          <view class="item acea-row row-between-wrapper" v-for="(item, index) in wyList" :key="index">
            <view>
              <view class="state">{{ item.content ? item.content : "系统发放补贴" }}</view>
              <view>{{ item.updateTime }}</view>
            </view>
            <view class="num font-color" style="color: #1ba035" v-if="item.isChanges == 1">+{{ item.integralAmount }}</view>
            <view class="num" v-else>-{{ item.integralAmount }}</view>
          </view>
          <view class="loadingicon acea-row row-center-wrapper" style="display: flex; align-items: center; justify-content: center" v-if="wyList.length > 0">
            <text class="loading iconfont icon-jiazai" :hidden="loadingWy == false"></text>{{ loadTitle }}
          </view>
          <view v-if="wyList.length == 0">
            <view style="text-align: center; padding: 10px; display: flex; flex-direction: column; align-items: center">
              <image class="" mode="aspectFit" src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/03/25/zwsj_20250325090754A001.png"> </image>
              <span style="font-family: PingFangSC, PingFang SC; font-weight: 400; font-size: 28rpx; color: #a8a8a8; line-height: 40rpx; text-align: center; font-style: normal"
                >暂无补贴记录哦～</span
              >
            </view>
          </view>
        </view>
        <view class="list" :hidden="current != 1">
          <view class="tip acea-row row-middle">
            <text class="iconfont icon-shuoming"></text>
            <text style="color: #ff7604">提示：输入手机号生成二维码，可将平台积分赠送给好友</text>
          </view>
          <view class="give-form">
            <view class="form-item">
              <view class="label">平台积分余额</view>
              <view class="value">{{ userInfo.gpWyPaymentAmount || 0 }}</view>
            </view>
            <view class="form-item">
              <view class="label">接收人手机号</view>
              <input type="number" v-model="giveForm.phone" placeholder="请输入接收人手机号" maxlength="11" />
            </view>
            <view class="form-item">
              <view class="label">赠送金额</view>
              <input type="digit" v-model="giveForm.amount" placeholder="请输入赠送金额" />
            </view>
            <view class="form-item">
              <button class="submit-btn" @click="generateQrCode">生成二维码</button>
            </view>
          </view>
          <view class="qr-code-container" v-if="qrCodeShow">
            <view class="qr-code-title">请将二维码发送给好友</view>
            <!-- 修改为显示后端生成的小程序二维码 -->
            <image v-if="miniProgramQrCode" class="qr-code" :src="miniProgramQrCode" mode="widthFix"></image>
            <view class="qr-code-desc">好友扫码即可领取平台积分</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { postIntegralUser, wyjfList, sharecodesss } from "../../../utils/api/local";
import tkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue";
import { getUserInfo } from "../../../utils/request_api.js";
import { getQrcode } from "../../../utils/request_api.js";
export default {
  components: {
    tkiQrcode,
  },
  data() {
    return {
      current: "",
      pageNum: 1,
      pageSize: 10,
      wyList: [],
      integral: {},
      loadendWy: false,
      loadingWy: false,
      loadTitle: "加载更多",
      userInfo: "",
      giveForm: {
        phone: "",
        amount: "",
      },
      qrCodeValue: "",
      qrCodeShow: false,
      miniProgramQrCode: "",
    };
  },
  /*   watch: {
    userInfo: {
      handler: function (newV, oldV) {
        if (newV) {
          this.getUserInfo1();
          this.getwyjfList();
        }
      },
      deep: true,
    },
  }, */
  onLoad(options) {
    this.current = options.type || 0;
    this.getUserInfo1();
    this.getwyjfList();
  },
  onReachBottom: function () {
    if (this.current === 0) {
      this.getwyjfList();
    }
  },
  methods: {
    getUserInfo1() {
      getUserInfo()
        .then((res) => {
          if (res.code === 401) {
            uni.showToast({
              title: "您的登录已过期，请重新登录",
              icon: "none",
            });
            uni.switchTab({
              url: "/pages_h5/myCenter/index",
            });
            // return;
          } else {
            this.userInfo = res.data;
            uni.setStorageSync("userInfo", res.data);
          }
        })
        .catch((err) => {
          console.error("获取用户信息失败", err);
        });
    },
    getwyjfList: function () {
      let that = this;
      if (that.loadingWy) return;
      if (that.loadendWy) return;
      that.loadingWy = true;
      that.loadTitle = "";
      wyjfList({
        pageNum: that.pageNum,
        pageSize: that.pageSize,
        ebUserId: uni.getStorageSync("uid"),
      }).then(
        function (res) {
          let list = res.rows,
            loadendWy = list.length < that.pageSize;
          that.wyList = that.wyList.concat(list);
          that.pageNum = that.pageNum + 1;
          that.loadingWy = false;
          that.loadendWy = loadendWy;
          that.loadTitle = loadendWy ? "哼~😕我也是有底线的~" : "加载更多";
        },
        function (err) {
          console.error("获取平台积分列表失败", err);
          that.loadingWy = false;
          that.loadTitle = "加载更多";
        },
      );
    },
    nav: function (current) {
      console.log("🚀 ~ current:", current);
      this.current = current;
      if (this.current == 0) {
        this.loadendWy = false;
        this.loadingWy = false;
        this.pageNum = 1;
        this.wyList = [];
        this.getwyjfList();
      }
    },
    generateQrCode() {
      // 验证手机号
      if (!this.giveForm.phone) {
        uni.showToast({
          title: "请输入手机号",
          icon: "none",
        });
        return;
      }

      // 验证手机号格式
      if (!/^1[3-9]\d{9}$/.test(this.giveForm.phone)) {
        uni.showToast({
          title: "手机号格式不正确",
          icon: "none",
        });
        return;
      }

      // 验证金额
      if (!this.giveForm.amount) {
        uni.showToast({
          title: "请输入赠送金额",
          icon: "none",
        });
        return;
      }

      const amount = parseFloat(this.giveForm.amount);
      if (isNaN(amount) || amount <= 0) {
        uni.showToast({
          title: "赠送金额必须大于0",
          icon: "none",
        });
        return;
      }

      // 检查余额是否充足
      const balance = parseFloat(this.userInfo.gpWyPaymentAmount || 0);
      if (amount > balance) {
        uni.showToast({
          title: "余额不足",
          icon: "none",
        });
        return;
      }
      var uid = uni.getStorageSync("uid");
      const timestamp = new Date().getTime(); // 获取当前时间戳
      const randomNum = Math.floor(Math.random() * 9000) + 1000; // 生成1000-9999之间的四位随机数
      const shareCode = timestamp + "" + randomNum; // 拼接时间戳和四位随机数
      sharecodesss({ shareCode: shareCode, ebUserIdShare: uid, comunityIntegralShare: amount }).then((res) => {
        console.log("🚀 ~ generateQrCode ~ res:", res);
      });

      // 调用后端生成小程序二维码
      this.getQrcodess(uid, amount, shareCode);
    },
    getQrcodess(uid, amount, shareCode) {
      // 拼接完整参数
      const paramPath =
        "pages_h5/myCenter/index?" + "uid=" + uid + "&type=3" + "&amount=" + amount + "&fromPhone=" + (this.userInfo.phone || "") + "&fromNickname=" + this.userInfo.nickname ||
        "" + "&toPhone=" + this.giveForm.phone + "&shareCode=" + shareCode;

      getQrcode({
        paramPath: paramPath,
      })
        .then((res) => {
          if (res.code === 200) {
            this.miniProgramQrCode = "data:image/png;base64," + res.msg;
            this.qrCodeShow = true;

            uni.showToast({
              title: "二维码生成成功",
              icon: "success",
            });
          } else {
            uni.showToast({
              title: res.msg || "生成二维码失败",
              icon: "none",
            });
          }
        })
        .catch((err) => {
          console.error("生成二维码失败", err);
          uni.showToast({
            title: "生成二维码失败",
            icon: "none",
          });
        });
    },
  },
};
</script>

<style scoped lang="scss">
.integral-details .header {
  background-image: url("");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  width: 100%;
  height: 360rpx;
  font-size: 72rpx;
  color: #fff;
  padding: 31rpx 0 45rpx 0;
  box-sizing: border-box;
  text-align: center;
  font-family: "Guildford Pro";
}

.integral-details .header .currentScore {
  font-size: 32rpx;
  color: rgba(255, 255, 255, 0.8);
  text-align: center;
  margin-bottom: 11rpx;
}

.integral-details .header .scoreNum {
  font-family: "Guildford Pro";
  font-size: 40rpx;
}

.integral-details .header .line {
  width: 60rpx;
  height: 3rpx;
  background-color: #fff;
  margin: 20rpx auto 0 auto;
}

.integral-details .header .nav {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.8);
  flex: 1;
  margin-top: 35rpx;
}

.integral-details .header .nav .item {
  width: 100%;
  text-align: center;
}

.integral-details .header .nav .item .num {
  color: #fff;
  font-size: 40rpx;
  margin-bottom: 5rpx;
  font-family: "Guildford Pro";
}

.integral-details .wrapper .nav {
  flex: 1;
  width: 690rpx;
  border-radius: 20rpx 20rpx 0 0;
  margin: -96rpx auto 0 auto;
  background-color: #f7f7f7;
  height: 96rpx;
  font-size: 30rpx;
  color: #bbb;
  display: flex;
  align-items: center;
}

.integral-details .wrapper .nav .item {
  text-align: center;
  width: 50%;
  color: rgb(86, 83, 83);
}

.integral-details .wrapper .nav .item.on {
  background-color: #fff;
  color: #272626;
  font-weight: bold;
  border-radius: 20rpx 0 0 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.integral-details .wrapper .nav .item:nth-of-type(2).on {
  border-radius: 0 20rpx 0 0;
}

.integral-details .wrapper .nav .item .iconfont {
  font-size: 38rpx;
  margin-right: 10rpx;
}

.integral-details .wrapper .list {
  background-color: #fff;
  padding: 24rpx 30rpx;
}

.integral-details .wrapper .list .tip {
  font-size: 25rpx;
  width: 690rpx;
  height: 60rpx;
  border-radius: 50rpx;
  background-color: #fff5e2;
  border: 1rpx solid #ffeac1;
  color: #c8a86b;
  padding: 0 20rpx;
  box-sizing: border-box;
  margin-bottom: 24rpx;
}

.integral-details .wrapper .list .tip .iconfont {
  font-size: 35rpx;
  margin-right: 15rpx;
}

.integral-details .wrapper .list .item {
  height: 124rpx;
  border-bottom: 1rpx solid #eee;
  font-size: 24rpx;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.integral-details .wrapper .list .item .state {
  font-size: 28rpx;
  color: #282828;
  margin-bottom: 8rpx;
}

.integral-details .wrapper .list .item .num {
  font-size: 36rpx;
  font-family: "Guildford Pro";
}

.give-form {
  padding: 20rpx 0;
}

.form-item {
  margin-bottom: 30rpx;
  padding: 0 20rpx;
}

.form-item .label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.form-item input {
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.form-item .value {
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  line-height: 80rpx;
  color: #666;
}

.submit-btn {
  background-color: #ff7604;
  color: #fff;
  border: none;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 10rpx;
  font-size: 32rpx;
}

.qr-code-container {
  text-align: center;
  padding: 30rpx 0;
}

.qr-code-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 30rpx;
}

.qr-code {
  margin: 0 auto 30rpx;
}

.qr-code-desc {
  font-size: 28rpx;
  color: #999;
}
</style>
